<?php
class menu
{
    private $db;
    private $table;
    public $pages;
    

    public function __construct() {
        global $db;
        $this->db = &$db;
        $this->table = DB_PRE.'menu';
    }

    public function get_submenu($menuid, $canview, $siteid=false)
    {
        if( is_array( $canview ) )
		{
			if( sizeof( $canview ) <= 0 )
			{
				return array();
			}
			else
			{
				$canview = ' and id in(\'' . implode( "','", $canview ) . '\')';
			}
		}
		else
		{
			$canview = '';
		}
		$sql_add = '';
		if($siteid !== false)
		{
			$sql_add = ' and siteid=?';	
		}
        $this->db->prepare("select * from $this->table where parentid=? and status=? {$sql_add} {$canview} order by listorder desc,id desc");
        $this->db->set_string($menuid);
        $this->db->set_int(STATUS_NORMAL);
        if($siteid !== false)
        {
        	$this->db->set_string($siteid);
        }
        $data = $this->db->execute();
        return $data;
    }
    
    
    /*
    	创建网站菜单
	    网站根目录
	    栏目根目录
	    各个模块目录
	    前台模板管理目录
	    站点配置管理
	    用户信息修改
    */
    public function make_site_menu($siteid)
    {
    	global $site_default_menu;
    	include_once 'site.class.php';
    	$site = new site();
    	$info = $site->get_one($siteid);
    	if(!isset($info['id']))
    	{
    		return false;
    	}
    	
    	$root = array(
    		'name'	      =>  $info['sitename'],
           	'parentid'    =>  MENU_SITE_ROOT_ID,
            'siteid'	  =>  $siteid,
            'url'         =>  '',
            'isfolder'    =>  1,
            'isopen'      =>  0 ,
            'image'       =>  '',
            'status'      =>  99,
    	);
    	$menu_root_id = $this->add($root);
    	if($menu_root_id === false)
    	{
    		return false;
    	}
    	$cat = array(
    		'name'	      =>  '站点设置',
           	'parentid'    =>  $menu_root_id,
            'siteid'	  =>  $siteid,
            'url'         =>  '',
            'isfolder'    =>  1,
            'isopen'      =>  0 ,
            'image'       =>  '',
            'status'      =>  99,
    	);
    	$menu_site_op_id = $this->add($cat);
    	foreach ($site_default_menu as $v)
    	{
    		$params = array(
    			'name'	      =>  $v['name'],
	           	'parentid'    =>  $menu_site_op_id,
	            'siteid'	  =>  $siteid,
	            'url'         =>  $v['url'],
	            'isfolder'    =>  0,
	            'isopen'      =>  0 ,
	            'image'       =>  '',
	            'status'      =>  99,
    		);
    		$this->add($params);
    	}
    	$params = array(
    		'name'	      =>  '新闻管理',
           	'parentid'    =>  $menu_root_id,
            'siteid'	  =>  $siteid,
            'url'         =>  '',
            'isfolder'    =>  1,
            'isopen'      =>  0 ,
            'image'       =>  '',
            'status'      =>  99,
    	);
    	$news_root_id = $this->add($params);
    	if($news_root_id === false)
    	{
    		return false;
    	}
    	$params = array(
    		'name'	      =>  '模块管理',
           	'parentid'    =>  $menu_root_id,
            'siteid'	  =>  $siteid,
            'url'         =>  '',
            'isfolder'    =>  1,
            'isopen'      =>  0 ,
            'image'       =>  '',
            'status'      =>  99,
    	);
    	$modules_root_id = $this->add($params);

        //添加更新缓存菜单
        $params = array(
    		'name'	      =>  '更新缓存',
           	'parentid'    =>  $menu_site_op_id,
            'siteid'	  =>  $siteid,
            'url'         =>  'admin/cache.php',
            'isfolder'    =>  0,
            'isopen'      =>  0 ,
            'image'       =>  '',
            'status'      =>  STATUS_NORMAL,
    	);
    	$this->add($params);

    	if($modules_root_id === false)
    	{
    		return false;
    	}
    	$menus = get_moudule_info();
    	$module_ids = explode(',', $info['modules']);
    	$menus_keys = array_keys($menus);
    	$diff = array_diff($menus_keys, $module_ids);
    	foreach ($menus as $k=>$v)
    	{
    		if(!in_array($k, $diff))
    		{
    			$add_menu_id[] = $k;
    		}
    	}
    	$site_info = array(
    		'id'			=>	$siteid,
    		'menusite'		=>	$menu_root_id,
    		'menunews'		=>	$news_root_id,
    		'menumodule'	=>	$modules_root_id,
    		'menusiteop'	=>	$menu_site_op_id
    	);
        $site->data = $site_info;
    	$site->update();
    	$this->add_site_module_menu($add_menu_id, $siteid);
    	return true;
    }
    
   	/**
   	 * 更新网站外围模块菜单
   	 *
   	 * @param array $modules
   	 * @param string $siteid
   	 */
    public function add_site_module_menu($modules, $siteid)
    {
    	include_once 'site.class.php';
    	$site = new site();
    	$info = $site->get_one($siteid);
    	$rootid = $info['menumodule'];
    	$this->del_site_module_menu($rootid, $siteid);
    	$menus = get_moudule_info();
    	foreach ($modules as $v)
    	{
    		$info = $menus[$v];
    		$params = array(
    			'name'	      =>  $info['title'],
		        'parentid'    =>  $rootid,
		        'siteid'	  =>  $siteid,
		        'url'         =>  '',
		        'isfolder'    =>  1,
		        'isopen'      =>  0 ,
		        'image'       =>  '',
		        'status'      =>  99,
    		);
    		$_pid = $this->add($params);
    		if(is_array($info['menu']))
    		{
    			$this->same_module_menu($siteid, $info['menu'],	$_pid, '',$info['name']);
    		}
    	}
    }
    
    /**
     * 递归的删除指定站点下指定目录下的子目录
     *
     * @param string $root_mid
     * @param string $siteid
     * @return true
     */
    private function del_site_module_menu($root_mid, $siteid)
    {
    	$subs = $this->get_submenu($root_mid, false, $siteid);
    	if(is_array($subs) && sizeof($subs) > 0)
    	{
	    	foreach ($subs as $s)
	    	{
	    		$rootid = $s['id'];
	    		$this->del_site_module_menu($rootid, $siteid);
	    	}
	    	$this->db->simple_update( $this->table, array( 'status'=>STATUS_DEL ), array( 'parentid' => $root_mid ) );
    	}
    	return true;
    }
    
    private function same_module_menu($siteid, $menus, $mpid, $pid,$name)
    {
    	foreach ($menus as $k=>$v)
    	{
    		if($v['parent'] == $pid)
    		{
    			$params = array(
    				'name'	      =>  $v['name'],
		           	'parentid'    =>  $mpid,
		            'siteid'	  =>  $siteid,
		            'url'         =>  $name.'/'.$v['url'],
		            'isfolder'    =>  0,
		            'isopen'      =>  0 ,
		            'image'       =>  '',
		            'status'      =>  99,
    			);
    			$_mpid = $this->add($params);
    			if($_mpid !== false)
    			{
    				$this->same_module_menu($siteid, $menus, $_mpid, $k,$name);
    				$this->update_isfolder_status( $mpid );
    			}
    		}
    	}
    }

    public function get( $menuid, $siteid=false )
    {
    	$add_sql = '';
    	if($siteid !== false)
    	{
    		$add_sql = ' and siteid=?';
    	}
        $this->db->prepare( "SELECT * FROM $this->table WHERE status=? and id = ? {$add_sql} LIMIT 1" );
        $this->db->set_int( STATUS_NORMAL );
        $this->db->set_string( $menuid );
        if($siteid !== false)
        {
        	$this->db->set_string($siteid);
        }
		$menu = $this->db->execute( true );
		return $menu;
    }

    public function get_keyid( $keyid )
    {
        $this->db->prepare( "SELECT * FROM $this->table WHERE status=? and keyid = ? LIMIT 1" );
        $this->db->set_int( STATUS_NORMAL );
        $this->db->set_string( $keyid );
		$menu = $this->db->execute( true );
		return $menu;
    }

    public function add( $data )
    {
        $params = $data;
        $res = $this->db->insert( $this->table, $params );
        if($res === false)
        {
        	return false;
        }
        return $this->db->uuid();
    }

    public function update( $menuid, $data )
    {
        return $this->db->simple_update( $this->table, $data, array( 'id' => $menuid ) );
    }

    public function update_isfolder_status( $menuid )
    {
        $isfolder = $this->get_submenu( $menuid, false ) ? 1 : 0;
        $params = array(
            'isfolder'    =>  $isfolder,
        );
        if( !$isfolder )
		{
			$r = $this->get( $menuid );
			$keyid = explode( '_', $r['keyid'] );
			if( trim( $keyid[0] ) == 'cat' )
			{
				$params['url'] = 'admin/content.php?catid=' . trim( $keyid[1] );
			}
		}
		else
		{
			$params['url'] = '';
		}
        
        return $this->update( $menuid, $params );
    }

    public function delete( $menuid )
    {
        return $this->update( $menuid, array( 'status'=>STATUS_DEL ) );
    }

    public function get_list( $params, $order, $canview, $page=1, $pagesize=10 )
    {
        $where = '';
        if( is_array( $params ) && sizeof( $params ) > 0 )
        {
            $where = ' where ';
            $where .= implode( ' and ', $params );
        }
        if( is_array( $canview ) )
		{
			if( sizeof( $canview ) <= 0 )
			{
				return array();
			}
			else
			{
				$canview = ' and id in(' . implode( ',', $canview ) . ')';
			}
		}
		else
		{
			$canview = '';
		}
        $where .= $canview;
        $where .= $order;
        $this->db->prepare( "SELECT count(*) as nums FROM $this->table" . $where );
		$res = $this->db->execute( true );
		$nums = isset( $res['nums'] ) ? intval( $res['nums'] ) : 0;
        $this->pages = pages( $nums, $page, $pagesize );
		$this->db->prepare( "SELECT * FROM $this->table" . $where . " limit ?, ?" );
		$this->db->set_int( ( $page-1 ) * $pagesize );
		$this->db->set_int( $pagesize );
	    $list = $this->db->execute();
        return $list;
    }

     /**
	 * 菜单信息排序
	 *
	 * @param ARRAY() $data
	 * @return 	BOOL
	 */
    public function listorder( $data )
    {
        if( !is_array( $data ) )
        {
            return false;
        }
        foreach( $data as $id => $listorder )
        {
            $listorder = intval( $listorder );
            $this->update( $id, array( 'listorder' => $listorder ) );
        }
        return true;
    }

    /**
	 * 检查同一父菜单下是否有重复的菜单名称
	 *
	 * @param INT $parentid，STRING $name
	 * @return 	ARRAY()  $menu
	 */
    public function check_name( $parentid, $name )
    {
        $this->db->prepare( "SELECT * FROM $this->table WHERE status=? and parentid = ? and name = ?" );
        $this->db->set_int( STATUS_NORMAL );
        $this->db->set_string( $parentid );
        $this->db->set_string( $name );
		$menu = $this->db->execute();
		return $menu;
    }
}
?>
